package com.example.gamecenter

import android.annotation.SuppressLint
import android.app.Application
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MyApplication : Application() {
    private val preloadedWebViews = mutableListOf<WebView>()
    private val job = Job()
    private val scope = CoroutineScope(Dispatchers.IO + job)
    override fun onCreate() {
        super.onCreate()
//        initPreloadWebView()
    }

    @SuppressLint("SetJavaScriptEnabled")
    fun initPreloadWebView() {
        val urls = listOf("https://h5itokenla.147358.top/index")
        for (url in urls) {
            scope.launch {
                val webView = WebView(applicationContext)
                webView.settings.javaScriptEnabled = true
                webView.settings.domStorageEnabled = true

                webView.webViewClient = object : WebViewClient() {
                    override fun onPageFinished(view: WebView?, url: String?) {
                        super.onPageFinished(view, url)
                        preloadedWebViews.add(webView)
//                       withContext(Dispatchers.Main) {
//                            preloadedWebViews.add(webView)
//                        }
                    }
                }
                webView.loadUrl(url)
            }
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        job.cancel()
        preloadedWebViews.forEach { it.destroy() }
    }

    fun getPreloadedWebViews(): List<WebView> {
        return preloadedWebViews
    }
}
